import React, { useState, useEffect } from 'react'
import { 
  Row, 
  Col, 
  Card, 
  Statistic, 
  Progress, 
  Table, 
  Tag, 
  Avatar,
  List,
  Typography,
  Badge
} from 'antd'
import { 
  UserOutlined, 
  ShoppingCartOutlined, 
  DollarOutlined,
  RiseOutlined,
  FallOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons'
import ReactECharts from 'echarts-for-react'
import './index.less'

const { Text } = Typography

// 模拟数据
const mockStatistics = {
  users: 1234,
  orders: 567,
  revenue: 89032,
  growth: 12.5
}

const mockChartData = {
  dates: ['01-01', '01-02', '01-03', '01-04', '01-05', '01-06', '01-07'],
  users: [120, 132, 101, 134, 90, 230, 210],
  orders: [220, 182, 191, 234, 290, 330, 310],
  revenue: [150, 232, 201, 154, 190, 330, 410]
}

const mockRecentOrders = [
  {
    id: '1',
    orderNo: 'ORD001',
    customer: '张三',
    amount: 299.00,
    status: 'completed',
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: '2',
    orderNo: 'ORD002',
    customer: '李四',
    amount: 599.00,
    status: 'pending',
    createTime: '2024-01-15 11:20:00'
  },
  {
    id: '3',
    orderNo: 'ORD003',
    customer: '王五',
    amount: 199.00,
    status: 'processing',
    createTime: '2024-01-15 12:10:00'
  }
]

const mockActivities = [
  {
    id: '1',
    user: '管理员',
    action: '创建了新用户',
    target: '张三',
    time: '2分钟前',
    type: 'create'
  },
  {
    id: '2',
    user: '李经理',
    action: '更新了订单状态',
    target: 'ORD001',
    time: '5分钟前',
    type: 'update'
  },
  {
    id: '3',
    user: '王编辑',
    action: '发布了文章',
    target: '系统升级公告',
    time: '10分钟前',
    type: 'publish'
  }
]

const Dashboard: React.FC = () => {
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    // 模拟数据加载
    const timer = setTimeout(() => {
      setLoading(false)
    }, 1000)

    return () => clearTimeout(timer)
  }, [])

  // 图表配置
  const getChartOption = () => ({
    title: {
      text: '数据趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['用户数', '订单数', '收入'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: mockChartData.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '用户数',
        type: 'line',
        data: mockChartData.users,
        smooth: true,
        lineStyle: {
          color: '#1890ff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
              { offset: 1, color: 'rgba(24, 144, 255, 0.1)' }
            ]
          }
        }
      },
      {
        name: '订单数',
        type: 'line',
        data: mockChartData.orders,
        smooth: true,
        lineStyle: {
          color: '#52c41a'
        }
      },
      {
        name: '收入',
        type: 'line',
        data: mockChartData.revenue,
        smooth: true,
        lineStyle: {
          color: '#faad14'
        }
      }
    ]
  })

  // 饼图配置
  const getPieOption = () => ({
    title: {
      text: '用户分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    },
    series: [
      {
        name: '用户分布',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 335, name: 'VIP用户' },
          { value: 310, name: '普通用户' },
          { value: 234, name: '新用户' },
          { value: 135, name: '流失用户' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })

  // 订单状态映射
  const statusMap = {
    completed: { color: 'success', text: '已完成' },
    pending: { color: 'warning', text: '待处理' },
    processing: { color: 'processing', text: '处理中' },
    cancelled: { color: 'error', text: '已取消' }
  }

  // 活动类型映射
  const activityTypeMap = {
    create: { icon: <CheckCircleOutlined />, color: '#52c41a' },
    update: { icon: <ExclamationCircleOutlined />, color: '#faad14' },
    publish: { icon: <RiseOutlined />, color: '#1890ff' },
    delete: { icon: <FallOutlined />, color: '#ff4d4f' }
  }

  const orderColumns = [
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
    },
    {
      title: '客户',
      dataIndex: 'customer',
      key: 'customer',
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount: number) => `¥${amount.toFixed(2)}`
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: keyof typeof statusMap) => (
        <Tag color={statusMap[status].color}>
          {statusMap[status].text}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    }
  ]

  return (
    <div className="dashboard">
      {/* 统计卡片 */}
      <Row gutter={[16, 16]} className="statistics-row">
        <Col xs={24} sm={12} lg={6}>
          <Card loading={loading}>
            <Statistic
              title="总用户数"
              value={mockStatistics.users}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card loading={loading}>
            <Statistic
              title="总订单数"
              value={mockStatistics.orders}
              prefix={<ShoppingCartOutlined />}
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card loading={loading}>
            <Statistic
              title="总收入"
              value={mockStatistics.revenue}
              prefix={<DollarOutlined />}
              precision={2}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card loading={loading}>
            <Statistic
              title="增长率"
              value={mockStatistics.growth}
              prefix={<RiseOutlined />}
              suffix="%"
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 图表区域 */}
      <Row gutter={[16, 16]} className="charts-row">
        <Col xs={24} lg={16}>
          <Card title="数据趋势" loading={loading}>
            <ReactECharts 
              option={getChartOption()} 
              style={{ height: '400px' }}
              notMerge={true}
              lazyUpdate={true}
            />
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card title="用户分布" loading={loading}>
            <ReactECharts 
              option={getPieOption()} 
              style={{ height: '400px' }}
              notMerge={true}
              lazyUpdate={true}
            />
          </Card>
        </Col>
      </Row>

      {/* 数据表格和活动列表 */}
      <Row gutter={[16, 16]} className="data-row">
        <Col xs={24} lg={14}>
          <Card title="最近订单" loading={loading}>
            <Table
              columns={orderColumns}
              dataSource={mockRecentOrders}
              rowKey="id"
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
        <Col xs={24} lg={10}>
          <Card title="最近活动" loading={loading}>
            <List
              itemLayout="horizontal"
              dataSource={mockActivities}
              renderItem={(item) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={
                      <Badge 
                        dot 
                        color={activityTypeMap[item.type as keyof typeof activityTypeMap]?.color}
                      >
                        <Avatar 
                          icon={activityTypeMap[item.type as keyof typeof activityTypeMap]?.icon}
                          size="small"
                        />
                      </Badge>
                    }
                    title={
                      <Text>
                        <strong>{item.user}</strong> {item.action} 
                        <Text code>{item.target}</Text>
                      </Text>
                    }
                    description={
                      <Text type="secondary">
                        <ClockCircleOutlined /> {item.time}
                      </Text>
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>

      {/* 进度指标 */}
      <Row gutter={[16, 16]} className="progress-row">
        <Col xs={24} sm={8}>
          <Card title="月度目标完成度" loading={loading}>
            <Progress 
              percent={75} 
              status="active"
              strokeColor={{
                from: '#108ee9',
                to: '#87d068',
              }}
            />
            <div style={{ marginTop: 16 }}>
              <Text type="secondary">目标：¥100,000</Text>
              <br />
              <Text type="secondary">当前：¥75,000</Text>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card title="用户活跃度" loading={loading}>
            <Progress 
              percent={85} 
              status="active"
              strokeColor="#52c41a"
            />
            <div style={{ marginTop: 16 }}>
              <Text type="secondary">活跃用户：1,050</Text>
              <br />
              <Text type="secondary">总用户：1,234</Text>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card title="订单转化率" loading={loading}>
            <Progress 
              percent={62} 
              status="active"
              strokeColor="#faad14"
            />
            <div style={{ marginTop: 16 }}>
              <Text type="secondary">转化订单：352</Text>
              <br />
              <Text type="secondary">总访问：567</Text>
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  )
}

export default Dashboard